package com.hy.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.ruiji.common.R;
import com.hy.ruiji.common.Status;
import com.hy.ruiji.common.customException;
import com.hy.ruiji.dto.OrdersDto;
import com.hy.ruiji.enyity.OrderDetail;
import com.hy.ruiji.enyity.Orders;
import com.hy.ruiji.enyity.User;
import com.hy.ruiji.service.OrderDetailService;
import com.hy.ruiji.service.OrdersService;
import com.hy.ruiji.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;

    /**
     * 用户下单
     * @param orders 提交的参数
     * @return 返回值
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("下单成功！");
    }

    /**
     * 用户对订单号进行分页查询
     * @param page 查询的页数
     * @param pageSize 每页数据大小
     * @return
     */
    @GetMapping("userPage")
    public R<Page> page(int page, int pageSize) {
        // 构造分页构造器
        Page<Orders> orderPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersPage = new Page<>();

        // 构造条件选择器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, Status.getCurrentId()); // 根据当前用户id查询
        wrapper.orderByDesc(Orders::getOrderTime); // 根据下单时间倒序

        // 执行查询
        ordersService.page(orderPage, wrapper);

        // 对象拷贝，避免直接复制 records 导致的遗漏
        BeanUtils.copyProperties(orderPage, ordersPage, "records");
        List<Orders> orderRecords = orderPage.getRecords();  // 获取查询到的原始订单记录

        // 将 Orders 转换为 OrdersDto，并将其设置到 ordersPage
        List<OrdersDto> records = orderRecords.stream().map(order -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            return ordersDto;
        }).collect(Collectors.toList());

        // 为每个订单设置对应的订单详情
        List<Long> orderIds = records.stream()
                .map(Orders::getId)  // 假设 getNumber 返回的是 String 类型，转换为 Long
                .collect(Collectors.toList());

        LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
        orderDetailWrapper.in(OrderDetail::getOrderId, orderIds);

        // 查询所有订单详情
        List<OrderDetail> allOrderDetails = orderDetailService.list(orderDetailWrapper);

        // 为每个订单设置对应的订单详情
        records.forEach(item -> {
            List<OrderDetail> details = allOrderDetails.stream()
                    .filter(detail -> detail.getOrderId().equals(item.getId()))
                    .collect(Collectors.toList());
            item.setOrderDetails(details);
        });

        // 将设置了订单详情的 records 设置到 ordersPage
        ordersPage.setRecords(records);

        // 返回成功结果
        return R.success(ordersPage);
    }

    /**
     * 商家查看订单详细信息
     * @param page 查看的页数
     * @param pageSize 每页大小
     * @param number 根据订单号查询
     * @param beginTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @GetMapping("/page")
    public R<Page> pageAll(int page, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> orderPage = new Page<>(page,pageSize);
        Page<OrdersDto> ordersPage = new Page<>();
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(number != null,Orders::getNumber,number);
        wrapper.between(beginTime != null && endTime != null,Orders::getOrderTime,beginTime,endTime);
        wrapper.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(orderPage,wrapper);
        BeanUtils.copyProperties(orderPage,ordersPage,"records");
        List<Orders> orderRecords = orderPage.getRecords();
        List<OrdersDto> records = orderRecords.stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            Long userId = item.getUserId();
            LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(User::getId,userId);
            User user = userService.getOne(wrapper1);
            ordersDto.setUserName(user.getName());
            return ordersDto;
        }).collect(Collectors.toList());

        ordersPage.setRecords(records);
        return R.success(ordersPage);
    }

    /**
     * 修改订单状态
     * @param orders 需要修改的状态
     * @return 返回结果
     */
    @PutMapping
    public R<String> updateOrder(@RequestBody Orders orders){
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId,orders.getId());
        //判断传入的订单状态是否已经完成
        if(orders.getStatus()>=5){
            throw new customException("订单已经完成，不要重复操作");
        }
        ordersService.update(orders, wrapper);
        return R.success("订单状态发生改变！");
    }
    /**
     * 再来一单
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        ordersService.orderAgain(orders);
        return R.success("加入成功！");
    }
}
